﻿
#include <iostream>
#include <vector>
#include <pcap/pcap.h>
#include <pcap/bpf.h>
#include <unistd.h>
#include "string.h"
#include "relay.h"

using std::cin;
using std::cout;
using std::endl;
using std::pair;
using std::vector;

extern bool is_online;

extern pcap_t *pcap_a;
extern pcap_t *pcap_b;

extern pcap_t *pcap_from;
extern pcap_t *pcap_to;

vector<PcapInfo> find_devs();

int main(int argc, char* argv[])
{
    vector<PcapInfo> devs = find_devs();
    
    int num = 1;
    for (vector<PcapInfo>::iterator it = devs.begin();it!=devs.end();++it) {
        cout<<num++<<"    "<<it->desc<<endl;
    }

    int A, B;
    cout<<"choose A:";
    cin>>A;

    cout<<"choose B:";
    cin>>B;
    
    is_online = false;

    cout<<devs[A-1].desc<<endl;
    cout<<devs[B-1].desc<<endl;

    rpcap_open(devs[A-1], pcap_a);
    rpcap_open(devs[B-1], pcap_b);
        
    if (fork()) {
        pcap_from = pcap_a;
        pcap_to = pcap_b;
        rpcap_loop(&devs[A-1], pcap_from);
    } else {
        pcap_from = pcap_b;
        pcap_to = pcap_a;
        rpcap_loop(&devs[B-1], pcap_from);
    }
    printf("OK\n");
    return 0;
}

vector<PcapInfo> find_devs()
{
	pcap_if_t *devs, *d;
	char errbuf[PCAP_ERRBUF_SIZE];
    vector<PcapInfo> ret;

	if (pcap_findalldevs(&devs, errbuf) == -1 || devs==NULL) {
		return ret; // 获取网卡失败
	}

    struct ifreq req;
    unsigned char mac_addr[6];
    int s = socket(AF_INET,SOCK_DGRAM, 0);

	for (d=devs; d; d=d->next) {
		if (!(d->flags & PCAP_IF_LOOPBACK) && strcmp(d->name, "any")!=0) {
            // 获取MAC地址
            strcpy(req.ifr_name, d->name);
            if (ioctl(s, SIOCGIFHWADDR, &req) != -1) {
                memcpy(mac_addr, req.ifr_hwaddr.sa_data, 6);
            } else {
                continue;
            }

            // 保存数据
            ret.push_back(PcapInfo(d->name, d->description ? d->description : d->name, mac_addr));
		}
	}

	pcap_freealldevs(devs);
    if (ret.empty()) {
        return ret; // 没有可用网卡
    }
    
    return ret;
}
